<!DOCTYPE html>

<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0, user-scalable=no"
        />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
    </head>

    <body>
        <script>
            let str = "2[1[a]3[b]2[3[c]4[d]]]";

            function smartRepeat(str) {
                // 指针
                let index = 0;
                // 栈1：存放数字
                let stack1 = [];
                // 栈2：存放临时字符串
                let stack2 = [];
                // 剩余字符串
                let rest = str;

                while (index < str.length - 1) {
                    rest = str.substring(index);

                    // 看当前剩余部分是不是以数字和[开头
                    if (/^\d+\[/.test(rest)) {
                        let item = Number(rest.match(/^(\d+)\[/)[1]);
                        stack1.push(item);
                        stack2.push("");
                        index += item.toString().length + 1;
                    } else if (/^\w+\]/.test(rest)) {
                        // 如果这个字符是字母，那么此时就把栈顶这项改为这个字母
                        let word = rest.match(/^(\w+)\]/)[1];
                        stack2[stack2.length - 1] = word;
                        index += word.length;
                    } else if (rest[0] === "]") {
                        // 如果这个字符是]，那么就①将stack1弹栈，②stack2弹栈，③把字符串栈的新栈顶的元素重复刚刚弹出的那个字符串指定次数拼接到新栈顶上。
                        let item = stack1.pop();
                        let word = stack2.pop();
                        stack2[stack2.length - 1] += word.repeat(item);
                        index++;
                    }
                }

                return stack2[0].repeat(stack1[0]);
            }

            console.log(smartRepeat(str));
        </script>
    </body>
</html>
